package io.renren.modules.clothingorder.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.JacksonUtils;
import io.renren.common.utils.PageData;
import io.renren.modules.clothingorder.dao.ClothingOrderDao;
import io.renren.modules.clothingorder.dto.ClothingOrderDTO;
import io.renren.modules.clothingorder.entity.ClothingOrderEntity;
import io.renren.modules.clothingorder.enums.StatusEnum;
import io.renren.modules.clothingorder.service.ClothingOrderService;
import io.renren.modules.clothingorder.vo.ClothingOrderVO;
import io.renren.modules.clothingpicture.service.ClothingPictureService;
import io.renren.modules.clothingpicture.vo.ClothingPictureVO;
import io.renren.modules.clothingtype.entity.ClothingTypeEntity;
import io.renren.modules.clothingtype.service.ClothingTypeService;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.user.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单表
 *
 * @author lzy lzy
 * @since 1.0.0 2021-08-30
 */
@Slf4j
@Service
public class ClothingOrderServiceImpl extends ServiceImpl<ClothingOrderDao, ClothingOrderEntity> implements ClothingOrderService {

    @Autowired
    private ClothingPictureService clothingPictureService;
    @Autowired
    private ClothingTypeService clothingTypeService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysUserService sysUserService;


    @Override
    public void save(ClothingOrderDTO clothingOrderDTO) {
        ClothingOrderEntity clothingOrderEntity = JacksonUtils.obj2pojo(clothingOrderDTO, ClothingOrderEntity.class);
        this.save(clothingOrderEntity);
    }

    @Override
    public void update(ClothingOrderDTO clothingOrderDTO) {
        ClothingOrderEntity clothingOrderEntity = JacksonUtils.obj2pojo(clothingOrderDTO, ClothingOrderEntity.class);
        this.updateById(clothingOrderEntity);
    }

    @Override
    public void addOrder(ClothingOrderDTO dto) {
        log.info("订单--(顾客)报价环节");
        // 订单编号
        long time = System.currentTimeMillis();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date(time));
        int number = (int)((Math.random()*9+1)*100000000);
        Long clothingTypeId = dto.getClothingTypeId();
        ClothingPictureVO clothingPictureVO = clothingPictureService.queryPictureByTypeId(clothingTypeId);
        //转换
        ClothingOrderEntity clothingOrderEntity = JacksonUtils.obj2pojo(dto, ClothingOrderEntity.class);
        clothingOrderEntity.setOrderSn("HIGH-"+format+"-"+number);
        this.baseMapper.insert(clothingOrderEntity);
    }

    @Override
    public PageData<ClothingOrderVO> getOrderPage(Map<String, Object> params) {
        log.info("获取登录用户的订单信息");
        // 获取当前的用户信息
        Long userId = SecurityUser.getUserId();
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
        Long roleId = roleIdList.get(0);
        // 获取信息
        String orderSn = (String) params.get("orderSn");
        Object startTime = params.get("startTime");
        Object endTime = params.get("endTime");
        Integer page = Integer.valueOf((String) params.get("page"));
        Integer limit = Integer.valueOf((String) params.get("limit"));
        Object status = params.get("status");
        QueryWrapper<ClothingOrderEntity> wrapper = new QueryWrapper<ClothingOrderEntity>();
        if (StringUtils.isNotBlank(orderSn)) {
            wrapper.like("order_sn",orderSn);
        }
        if (status != null){
            wrapper.eq("status",status);
        }
        if (startTime != null && endTime != null){
            wrapper.between("create_time",startTime,endTime);
        }
        if (roleId == 2L) {
            wrapper.eq("creator",userId);
        } else if (roleId == 3L) {
            wrapper.eq("designer_id",userId);
        }
        wrapper.orderByDesc("create_time");
        // 创建分页对象
        IPage<ClothingOrderEntity> iPage = new Page<ClothingOrderEntity>(page,limit);
        this.baseMapper.selectPage(iPage,wrapper);
        // 分页集合
        List<ClothingOrderEntity> records = iPage.getRecords();
        List<ClothingOrderVO> list = new ArrayList<>();
        records.forEach(e -> {
            ClothingOrderVO clothingOrderVO = JacksonUtils.obj2pojo(e, ClothingOrderVO.class);
            ClothingTypeEntity typeEntity = clothingTypeService.getById(e.getClothingTypeId());
            String dictName = typeEntity.getDictName();
            ClothingPictureVO clothingPictureVO = clothingPictureService.queryPictureByTypeId(typeEntity.getId());
            clothingOrderVO.setClothingTypeName(dictName);
            clothingOrderVO.setClothingPictureUrl(clothingPictureVO == null ? null : clothingPictureVO.getPicture());
            clothingOrderVO.setStatusName(StatusEnum.getValueByIndex(e.getStatus()));
            SysUserEntity sysUserEntity = sysUserService.queryUserByUserId(e.getDesignerId());
            clothingOrderVO.setDesignerName(sysUserEntity.getUsername());
            list.add(clothingOrderVO);
        });
        // 总数
        long total = iPage.getTotal();
        PageData<ClothingOrderVO> pageData = new PageData<ClothingOrderVO>(list,total);
        return pageData;
    }

    @Override
    public JSONObject getStatistics(Map<String, Object> params) {
        log.info("统计已定制订单数量、最多服装类型");
        JSONObject json = new JSONObject();
        QueryWrapper<ClothingOrderEntity> wrapper = new QueryWrapper<ClothingOrderEntity>();
        wrapper.eq("status",StatusEnum.DINGDANWANCHENG.getIndex());
        List<ClothingOrderEntity> clothingOrderEntities = this.baseMapper.selectList(wrapper);
        json.put("total",clothingOrderEntities.size());
        Map<Long, List<ClothingOrderEntity>> collect = clothingOrderEntities.stream().collect(Collectors.groupingBy(e -> e.getClothingTypeId()));
        Map<String,Object> map = new HashMap<>();
        List<JSONObject> jsonObjectList = new ArrayList<>();
        collect.keySet().forEach(e -> {
            JSONObject jsonObject = new JSONObject();
            ClothingTypeEntity clothingTypeEntity = clothingTypeService.getById(e);
            int size = collect.get(e).size();
            jsonObject.put("name",clothingTypeEntity.getDictName());
            jsonObject.put("value",size);
            jsonObjectList.add(jsonObject);
        });
        json.put("jsonObjectList",jsonObjectList);
        return json;
    }

    @Override
    public PageData<JSONObject> getHistoryPage(Map<String, Object> params) {
        log.info("获取历史订单服装列表");
        // 获取信息
        String designerName = (String) params.get("designerName");
        Object startTime = params.get("startTime");
        Object endTime = params.get("endTime");
        Integer page = Integer.valueOf((String) params.get("page"));
        Integer limit = Integer.valueOf((String) params.get("limit"));
        QueryWrapper<ClothingOrderEntity> wrapper = new QueryWrapper<ClothingOrderEntity>();

        if (StringUtils.isNotBlank(designerName)) {
            SysUserEntity sysUserEntity = sysUserService.queryByUserName(designerName);
            wrapper.eq("designer_id",sysUserEntity == null ? null : sysUserEntity.getUserId());
        }
        if (startTime != null && endTime != null){
            wrapper.between("create_time",startTime,endTime);
        }
        wrapper.eq("status",StatusEnum.DINGDANWANCHENG.getIndex());
        wrapper.orderByDesc("create_time");
        // 创建分页对象
        IPage<ClothingOrderEntity> iPage = new Page<ClothingOrderEntity>(page,limit);
        this.baseMapper.selectPage(iPage,wrapper);
        // 分页集合
        List<ClothingOrderEntity> records = iPage.getRecords();
        List<JSONObject> list = new ArrayList<>();
        records.forEach(e -> {
            JSONObject json = new JSONObject();
            ClothingTypeEntity typeEntity = clothingTypeService.getById(e.getClothingTypeId());
            String dictName = typeEntity.getDictName();
            SysUserEntity sysUser = sysUserService.queryUserByUserId(e.getDesignerId());
            json.put("dictName",dictName);
            json.put("productAmount",e.getProductAmount());
            json.put("designerPicture",e.getDesignerPicture());
            json.put("designerName",sysUser.getUsername());
            json.put("orderEvaluation",e.getOrderEvaluation());
            list.add(json);
        });
        // 总数
        long total = iPage.getTotal();
        PageData<JSONObject> pageData = new PageData<JSONObject>(list,total);
        return pageData;
    }

    @Override
    public void changeStatus(Long id, Integer status) {
        log.info("改变订单状态");
        UpdateWrapper<ClothingOrderEntity> wrapper = new UpdateWrapper<ClothingOrderEntity>();
        wrapper.eq("id",id);
        ClothingOrderEntity entity = new ClothingOrderEntity();
        entity.setStatus(status);
        this.baseMapper.update(entity,wrapper);
    }

    @Override
    public void upDesginerPic(ClothingOrderDTO dto) {
        log.info("设计师上传图稿环节");
        UpdateWrapper<ClothingOrderEntity> wrapper = new UpdateWrapper<ClothingOrderEntity>();
        wrapper.eq("id",dto.getId());
        ClothingOrderEntity entity = new ClothingOrderEntity();
        entity.setDesignerPicture(dto.getDesignerPicture());
        this.baseMapper.update(entity,wrapper);
    }


}
